﻿using System;
using System.IO;
using System.Windows;
using Ones.ViewModels;
using TweetSharp.Model;
using TweetSharp.Twitter.Service;
using System.Threading;

namespace Ones
{
    /// <summary>
    /// Interaction logic for AuthenticationWindow.xaml
    /// </summary>
    public partial class AuthenticationWindow : Window
    {
        private AuthorizationViewModel _authViewModel;
        private OAuthToken _token;
        private TwitterService _service;
        private bool _authenticated = false;

        public Boolean IsAuthenticated
        {
            get { return _authenticated; }
            private set
            {
                _authenticated = value;
            }
        }

        public TwitterService Service
        {
            get { return _service; }
        }

        public AuthenticationWindow()
        {
            InitializeComponent();

            _authViewModel = (AuthorizationViewModel)this.DataContext;

            _authViewModel.Load += new EventHandler(Load);
            _authViewModel.Authenticated += new EventHandler(Authenticated);

            _authViewModel.Start();
        }

        private void Authenticated(object sender, EventArgs e)
        {
            this.IsAuthenticated = true;
        }

        private void Load(object sender, EventArgs e)
        {
            ChangeStatus("Veryfing Twitter Authorization...");
            this.AuthorizeUser();
        }

        private void AuthorizeUser()
        {
            this.tbPinCode.IsEnabled = true;
            this.buttonAuthorize.IsEnabled = true;
            ChangeStatus("Asking for authorization in Twitter Server...");

            _token = _authViewModel.AskAuthorization();
        }

        private void buttonAuthorize_Click(object sender, RoutedEventArgs e)
        {
            if (!_authViewModel.IsAuthenticated)
            {
                try
                {
                    ChangeStatus("Authenticating " + _token.ScreenName + " at Twitter Server...");

                    _service = _authViewModel.Authorize(_token, tbPinCode.Text);

                    ChangeStatus("Authenticated.");

                    _authViewModel.IsAuthenticated = true;
                    this.Close();
                }
                catch (UnauthorizedAccessException ex)
                {
                    _authViewModel.IsAuthenticated = false;
                    Console.WriteLine(ex.Message);
                }
            }
            else
            {
                this.Close();
            }           
        }

        private void ChangeStatus(string text)
        {
            this.tbStatus.Text = text;
            Thread.Sleep(50);
        }
    }
}
